Popular Searches
Popular Course Categories
Popular Courses

Configuring Applications Using Properties and YAML

Configuring Applications Using Properties and YAML

Spring Boot Application Development

Configuring Applications Using Properties and YAML

Course: Advanced Java Training

Topic: Configuring Applications Using Properties and YAML in Spring Boot

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Application Configuration

Application configuration is the process of defining settings that control how an application behaves in different environments. In Spring Boot, configuration values can include the server port, application name, database connection details, logging levels, API endpoints, file locations, feature flags, and other operational settings.

Instead of hardcoding these values directly into Java classes, developers can store them in external configuration files. Spring Boot commonly supports two configuration formats: Properties and YAML.

Both formats allow developers to maintain application settings separately from business logic. This makes applications easier to configure, test, deploy, and maintain.

Why Is Application Configuration Important?

  • Separates configuration from Java source code.
  • Makes it easier to use different settings for development, testing, and production.
  • Reduces the need to modify source code when configuration values change.
  • Improves maintainability and readability.
  • Supports database, server, logging, security, and integration settings.
  • Allows configuration values to be supplied through environment variables and command-line arguments.
  • Helps teams manage application deployments consistently.

2. What Is an Application Properties File?

The application.properties file is a standard Spring Boot configuration file that stores settings as key-value pairs. Each configuration property generally appears on a separate line.

By default, the file is commonly placed inside src/main/resources, where Spring Boot can locate it when starting the application.

Example: application.properties

spring.application.name=student-management
server.port=8081
logging.level.root=INFO
spring.main.banner-mode=console

Explanation

  • spring.application.name defines the application name.
  • server.port specifies the HTTP server port for a web application.
  • logging.level.root sets the root logging level.
  • spring.main.banner-mode controls how the startup banner is displayed.

Property names must correspond to recognized Spring Boot properties or application-defined configuration keys. An unrecognized property may have no effect unless the application explicitly reads it.

3. What Is YAML Configuration?

YAML stands for YAML Ain't Markup Language. It is a text-based data serialization format that represents information using indentation, key-value pairs, lists, and nested structures.

Spring Boot supports YAML configuration through files such as application.yml or application.yaml. YAML can make hierarchical configuration easier to read because related settings can be grouped under parent keys.

Example: application.yml

spring:
  application:
    name: student-management

server:
  port: 8081

logging:
  level:
    root: INFO

spring:
  main:
    banner-mode: console

Important correction: A YAML mapping must not define the same key twice at the same level. To combine the settings above correctly, use one spring section, as shown here:

spring:
  application:
    name: student-management
  main:
    banner-mode: console

server:
  port: 8081

logging:
  level:
    root: INFO

Advantages of YAML

  • Represents nested configuration in a readable structure.
  • Groups related settings under common parent keys.
  • Supports lists and structured data.
  • Can reduce repeated prefixes in configuration files.
  • Is useful when an application has multiple related configuration settings.

4. Properties vs. YAML

Feature Properties YAML
File extension .properties .yml or .yaml
Structure Flat key-value entries Nested mappings and lists
Hierarchy Expressed using dotted property names Expressed primarily through indentation
Readability Simple for a small number of settings Often convenient for nested settings
Lists Can use indexed property keys Can use dash-prefixed list items
Comments Use # Use #
Common errors Incorrect keys or values Incorrect indentation, duplicate keys, or invalid YAML syntax
Spring Boot support Supported Supported

Neither format is universally better. Use the format that fits the team's conventions and the complexity of the configuration. A project should generally maintain a clear, consistent configuration strategy.

5. Creating Configuration in application.properties

The application.properties file stores configuration as individual key-value pairs. It is normally located inside src/main/resources.

Example Configuration

spring.application.name=student-management
server.port=8081

app.college.name=ABC College
app.college.location=Mumbai
app.college.website=https://example.com

logging.level.root=INFO
logging.level.com.example.studentapi=DEBUG

In this example, standard Spring Boot properties configure the application name, server port, and logging. The app.college.* keys are custom properties that the application can read using Spring's configuration facilities.

Reading a Property Using @Value

The @Value annotation injects an individual configuration value into a Spring-managed bean.

package com.example.studentapi;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class CollegeInformation {

    @Value("${app.college.name}")
    private String collegeName;

    @Value("${app.college.location}")
    private String collegeLocation;

    public void displayInformation() {
        System.out.println("College: " + collegeName);
        System.out.println("Location: " + collegeLocation);
    }
}

Spring resolves the placeholders using the application's environment. If a required property cannot be resolved and no default is provided, application startup or bean creation may fail.

Using a Default Value

@Value("${app.college.name:Default College}")
private String collegeName;

The expression provides Default College when the property is not configured through another available property source.

6. Creating Configuration in application.yml

YAML represents nested values using indentation. It is useful for grouping related settings in a readable hierarchy.

Example YAML Configuration

spring:
  application:
    name: student-management

server:
  port: 8081

app:
  college:
    name: ABC College
    location: Mumbai
    website: https://example.com

logging:
  level:
    root: INFO
    com.example.studentapi: DEBUG

Notice that indentation defines the relationship between parent and child keys. Use spaces rather than tabs, and keep indentation consistent.

Important YAML Rules

  • Use indentation to represent nested structures.
  • Do not use tabs for indentation.
  • Keep key names consistent and avoid accidental duplicate keys.
  • Use quotes when a value could be interpreted ambiguously or needs special characters handled explicitly.
  • Use a dash (-) to represent an item in a YAML list.
  • Use # to add comments.

Example of a YAML List

app:
  supported-languages:
    - English
    - Hindi
    - Marathi

This configuration represents a list of three supported languages under the app.supported-languages property.

7. Organizing Configuration with @ConfigurationProperties

When an application contains multiple related custom properties, using @ConfigurationProperties is often cleaner than injecting each property separately with @Value. It groups related settings into a Java class and supports type-safe binding.

Step 1: Define the Properties Class

package com.example.studentapi.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "app.college")
public class CollegeProperties {

    private String name;
    private String location;
    private String website;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }
}

Step 2: Enable Configuration Properties

Register the properties class so Spring Boot can bind the configured values to it. One option is to use @ConfigurationPropertiesScan on the main application class when the properties class is in a package covered by the scan.

package com.example.studentapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan
public class StudentApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudentApiApplication.class, args);
    }
}

Step 3: Inject the Properties Bean

package com.example.studentapi.service;

import com.example.studentapi.config.CollegeProperties;
import org.springframework.stereotype.Service;

@Service
public class CollegeService {

    private final CollegeProperties properties;

    public CollegeService(CollegeProperties properties) {
        this.properties = properties;
    }

    public String getCollegeInformation() {
        return properties.getName()
                + " - " + properties.getLocation();
    }
}

Constructor injection makes the dependency explicit and makes the service easier to test. The properties class can be extended with additional fields as the application requirements grow.

When to Use @ConfigurationProperties

  • When several related configuration values belong together.
  • When configuration should be mapped to appropriate Java data types.
  • When a project benefits from a clear configuration object.
  • When validation of configuration values is required.

For configuration validation, Spring Boot supports validation annotations when the appropriate validation dependency is present. You can use constraints such as @NotBlank or @Min on suitable fields and enable validation on the configuration properties class.

8. Using Spring Profiles for Different Environments

Applications commonly run in different environments, such as development, testing, staging, and production. Each environment may require different ports, database URLs, logging levels, or service endpoints.

Spring profiles allow configuration to vary by environment without requiring separate application codebases.

Common Profile Files

src/main/resources/
├── application.properties
├── application-dev.properties
├── application-test.properties
└── application-prod.properties

For YAML-based configuration, equivalent filenames can be used, such as application-dev.yml and application-prod.yml.

Development Configuration

# application-dev.properties
server.port=8081
logging.level.com.example.studentapi=DEBUG

Production Configuration

# application-prod.properties
server.port=8080
logging.level.root=WARN

These files are examples of environment-specific settings. Production database credentials and other secrets should be supplied securely through an appropriate secret-management system or deployment environment rather than committed to source control.

Activating a Profile

You can activate a profile through an environment variable:

SPRING_PROFILES_ACTIVE=dev

You can also activate a profile through a command-line argument when launching the application:

java -jar student-api.jar --spring.profiles.active=dev

For local development, an IDE can also provide environment variables or program arguments in its run configuration. Use the appropriate syntax for your operating system and launch method.

9. Configuration Precedence and Overrides

Spring Boot can obtain configuration values from several sources, including packaged configuration files, external configuration files, environment variables, Java system properties, and command-line arguments. These sources have a defined precedence, so a value supplied by a higher-priority source can override a value from a lower-priority source.

Example: Overriding the Server Port

Suppose the packaged application.properties file contains:

server.port=8080

You can start the application with a different port:

java -jar student-api.jar --server.port=9090

When this command-line property is applied, the application uses port 9090 instead of the packaged default, provided no startup issue prevents the server from binding to that port.

Why Configuration Precedence Matters

  • It allows deployments to override defaults without rebuilding the application.
  • It supports environment-specific configuration.
  • It can explain why an application is using a value different from the one in its packaged file.
  • It helps developers diagnose configuration problems during deployment.

When investigating a surprising property value, inspect the active profile, environment variables, command-line arguments, external configuration locations, and application startup logs.

10. Externalizing Configuration and Managing Secrets

Externalized configuration means keeping environment-dependent settings outside the application code and, where appropriate, outside the packaged JAR. This allows the same application artifact to be deployed into multiple environments with different settings.

Example: Database Configuration

spring.datasource.url=${DB_URL}
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}

Here, the values are supplied through environment variables named DB_URL, DB_USERNAME, and DB_PASSWORD. The application environment must define these variables before startup, and a compatible database driver and relevant data-access dependencies must be included.

Security Best Practices

  • Do not hardcode production passwords, API keys, or access tokens in Java classes.
  • Do not commit real credentials to Git repositories.
  • Use deployment environment variables or an appropriate secret manager.
  • Restrict access to production configuration files.
  • Use separate credentials for development, testing, and production.
  • Rotate credentials according to your organization's security policies.
  • Avoid printing secrets in application logs or error messages.

11. Common Configuration Mistakes

Problem Possible Cause Solution
Property value is not loaded File is in the wrong location or the key is incorrect. Check that the configuration file is under the expected resources or external configuration location and verify the key name.
YAML parsing error Incorrect indentation, tabs, or invalid YAML syntax. Use spaces consistently and validate the YAML structure.
Unexpected configuration value A higher-priority source overrides the file value. Inspect active profiles, environment variables, command-line arguments, and external files.
Profile-specific settings do not apply The intended profile is not active or the filename is incorrect. Check the profile name and use a matching file such as application-dev.properties.
Application fails because of a missing placeholder A required configuration value has not been supplied. Define the property or provide an appropriate default where suitable.
Database connection fails Incorrect URL, unavailable database, missing driver, or invalid credentials. Verify the database service, connection URL, dependency, credentials, and network connectivity.
Port binding fails Another process already uses the configured port. Stop the conflicting process or configure an available port.
Configuration class is not populated The class is not registered for configuration-property binding or its prefix does not match. Check the prefix and use configuration-properties scanning or explicit registration.

12. Practical Project: Configure a Student Management Application

Objective: Create a Spring Boot application and use external configuration to define its application name, server port, and college information.

Step 1: Create the Project

Open Spring Initializr, select Maven and Java, choose a compatible Spring Boot version, and add the Spring Web dependency.

Step 2: Create application.properties

spring.application.name=student-management
server.port=8081

app.college.name=ABC College
app.college.location=Mumbai

Step 3: Create a REST Controller

package com.example.studentapi;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CollegeController {

    @Value("${app.college.name}")
    private String collegeName;

    @Value("${app.college.location}")
    private String location;

    @GetMapping("/college")
    public String getCollege() {
        return collegeName + " is located in " + location;
    }
}

Step 4: Run the Application

Run the main application class from the IDE, or use the Maven wrapper from the project directory.

# Windows
mvnw.cmd spring-boot:run

# macOS or Linux
./mvnw spring-boot:run

Step 5: Test the Endpoint

Open the following URL in a browser or API client:

http://localhost:8081/college

Expected response:

ABC College is located in Mumbai

Step 6: Try a Different Environment

Create an application-dev.properties file and add a different port or logging level. Activate the dev profile and verify that the environment-specific configuration is applied.

13. Best Practices

  • Keep configuration separate from business logic.
  • Use meaningful property names grouped by application feature.
  • Choose either Properties or YAML as the primary format for a given application where practical.
  • Use @ConfigurationProperties for groups of related custom settings.
  • Use profiles for environment-specific behavior.
  • Keep secrets out of source control.
  • Validate required configuration values early.
  • Document non-obvious settings and their expected values.
  • Test configuration for development, testing, and production scenarios.
  • Check the official Spring Boot documentation when configuring version-specific features.

14. Interview Questions and Answers

Q1. What is application configuration in Spring Boot?

Answer: It is the process of defining settings that control application behavior, such as server ports, database connectivity, logging, and custom application values.

Q2. What is the purpose of application.properties?

Answer: It stores configuration as key-value pairs and is commonly placed in src/main/resources.

Q3. What is the difference between Properties and YAML?

Answer: Properties files use flat key-value entries, while YAML represents nested structures through indentation and supports lists in a readable format.

Q4. What is the purpose of @Value?

Answer: It injects an individual property value into a Spring-managed component using a placeholder expression.

Q5. What is @ConfigurationProperties?

Answer: It binds a group of related configuration properties to a Java object, providing structured and type-safe configuration.

Q6. What are Spring profiles?

Answer: Profiles allow an application to use different configuration settings for environments such as development, testing, and production.

Q7. Can environment variables override configuration files?

Answer: Yes. Spring Boot has a defined configuration precedence, and environment variables or other higher-priority sources can override file-based values.

Q8. How can you change the server port?

Answer: Set server.port in a configuration file or supply an override such as --server.port=9090 when launching the application.

Q9. Why should secrets not be stored in source code?

Answer: Source code can be shared, backed up, or committed to repositories. Keeping secrets in suitable external secret stores or protected deployment configuration reduces accidental exposure.

Q10. What should you check when a property does not take effect?

Answer: Check the property name, file location, active profile, environment variables, command-line arguments, external configuration files, and application logs.

15. Quick Revision Checklist

  • Understand the role of externalized configuration in Spring Boot.
  • Know the difference between application.properties and application.yml.
  • Understand how @Value injects individual configuration values.
  • Use @ConfigurationProperties for related configuration groups.
  • Know how to activate and use Spring profiles.
  • Understand how configuration sources override one another.
  • Keep passwords and sensitive values out of source control.
  • Test configuration changes by running the application and checking its behavior.

16. Conclusion

Properties and YAML are essential tools for configuring Spring Boot applications. They allow developers to separate application settings from Java code, organize related values, adapt applications to different environments, and manage deployment configuration more effectively.

By learning how to define properties, bind them to Java classes, use Spring profiles, override values safely, and troubleshoot configuration issues, developers can build Spring Boot applications that are easier to maintain and deploy.


Useful Learning Links

Previous Next
whatsapp